<template>
  <a-spin :spinning="spinning">
    <a-empty v-if="showEmpty" />
    <div v-else :id="id"></div>
  </a-spin>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import { Chart } from '@antv/g2';
export default defineComponent({
  name: 'RingChart',
  props: {
    id: {
      type: String,
      required: true
    },
    data: {
      type: Array,
      required: true
    }
  },
  setup(props) {
    const initLineChart = (data) => {
      const chart = new Chart({
        container: props.id,
        autoFit: true,
        height: 150
      });
      chart.data(data);
      chart.scale('persent', {
        formatter: (val) => {
          console.log(val);
          val = val.toFixed(2) * 100 + '%';
          return val;
        }
      });
      chart.coordinate('theta', {
        radius: 0.9,
        innerRadius: 0.5
      });
      chart.tooltip({
        showTitle: false,
        showMarkers: false,
        itemTpl:
          '<li class="g2-tooltip-list-item"><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>'
      });
      // 辅助文本
      chart.annotation().text({
        position: ['50%', '50%'],
        content: '主机',
        style: {
          fontSize: 16,
          fill: '#333',
          textAlign: 'center'
        }
      });
      chart.legend({
        position: 'right'
      });
      chart
        .interval()
        .adjust('stack')
        .position('persent')
        .color('item')
        .label('persent', () => {
          return {
            offset: -15,
            style: {
              textAlign: 'center',
              shadowBlur: 2,
              fontSize: 10,
              shadowColor: 'rgba(0, 0, 0, .45)',
              fill: '#fff'
            }
          };
        })
        .tooltip('item*persent', (item, persent) => {
          persent = persent.toFixed(2) * 100 + '%';
          return {
            name: item,
            value: persent
          };
        });

      chart.interaction('element-active');
      chart.render();
    };
    const showEmpty = ref(false);
    const spinning = ref(false);
    onMounted(() => {
      spinning.value = true;
      setTimeout(() => {
        initLineChart(props.data);
        spinning.value = false;
      }, 1000);
    });
    return {
      initLineChart,
      showEmpty,
      spinning
    };
  }
});
</script>

<style scoped lang="less"></style>
